import {
  createSlice
} from '@reduxjs/toolkit';

const createRandom = () => {
  return new Date().getTime() + '_' + Math.random()
}

const COLOR = ['light', 'dark']
const SKIN_KEY = 'skin'
const LAYOUT_KEY = 'horizontal' // vertical    horizontal

const getQueryVariable = (variable) => {
  let query = window.location.href.split('?');
  if (query.length >= 2) {
    let vars = query[1].split("&");
    for (let i = 0; i < vars.length; i++) {
      let pair = vars[i].split("=");
      if (pair[0] == variable) {
        return pair[1]
      }
    }
  }
  return false
}

const getSkinH = () => {
  let skin = getQueryVariable(SKIN_KEY)
  if (skin) {
    setSkinH(skin)
  } else {
    skin = localStorage.getItem(SKIN_KEY)
  }
  if (COLOR.indexOf(skin) < 0) {
    skin = D_COLOR
  }
  changeTheme(skin)
  return skin
}

const setSkinH = (skin) => {
  if (COLOR.indexOf(skin) < 0) {
    skin = D_COLOR
  }
  localStorage.setItem(SKIN_KEY, skin)
  changeTheme(skin)
}

const changeTheme = (skin) => {
  document.documentElement.className = "custom-" + skin;
  document
    .getElementById("antd-style")
    .setAttribute("href", `./static/css/antd.${skin}.min.css`);
}

const getLayout = () => {
  let layout = getQueryVariable(LAYOUT_KEY)
  if (layout) {
    setLayoutH(layout)
  } else {
    layout = localStorage.getItem(LAYOUT_KEY)
  }
  layout = layout == 'vertical' ? 'vertical' : 'horizontal'
  return layout
}

const setLayoutH = (layout) => {
  localStorage.setItem(LAYOUT_KEY, layout)
}

export const commonSlice = createSlice({
  name: 'common',
  initialState: {
    skin: getSkinH(),
    sidebarWidth: createRandom(),
    layout: getLayout(),
    routerData: {
      breadcrumb: [],
    },
  },
  reducers: {
    setSkin: (state, action) => {
      let skin = action.payload
      setSkinH(skin)
      state.skin = skin
    },
    setLayout: (state, action) => {
      let layout = action.payload
      setLayoutH(layout)
      state.layout = layout
    },
    setSidebarWidth: (state, action) => {
      state.sidebarWidth = createRandom();
    },
    setRouterData: (state, {
      payload
    }) => {
      state.routerData = payload
    },
  }
});

export const {
  setSkin,
  setLayout,
  setSidebarWidth,
  setRouterData
} = commonSlice.actions;

export const common = state => state.common;

export default commonSlice.reducer;
